<!-- 采购商品 - 编辑 -->
<template>
  <view class="purchaseDetails">
    <view class="details_box">
      <view class="title"> 编辑详情 </view>
      <!-- 0：套餐 、1：粮油、2：营养餐、 3：自选增量（老师，学生）4：早餐 -->
      <!-- 套餐类型 -->
      <van-cell-group v-if="order_type == '0'">
        <my-picker
          :form="addForm"
          name="menu_name"
          @click-input="changeSetmeal"
          :columns="setmealList"
          value-key="menu_name"
          label="套餐选择"
          placeholder="请选择套餐"
        ></my-picker>
        <van-field
          :value="addForm.goods_name"
          readonly
          label="套餐名"
        ></van-field>
        <van-field
          :value="addForm.goods_num"
          name="goods_num"
          data-name="goods_num"
          @input="changeAddFormData"
          required
          clearable
          label="老师数量"
          placeholder="请填写数量"
        ></van-field>
        <van-field
          :value="addForm.goods_num_stu"
          name="goods_num_stu"
          data-name="goods_num_stu"
          @input="changeAddFormData"
          required
          clearable
          label="学生数量"
          placeholder="请填写数量"
        ></van-field>
        <van-field :value="addForm.foods_name" readonly label="包含菜名">
          <view slot="input">
            {{ addForm.foods_name }}
          </view>
        </van-field>
        <van-field
          :value="addForm.supplier_name"
          name="supplier_name"
          data-name="supplier_name"
          @input="changeAddFormData"
          required
          clearable
          label="供应商名称"
          placeholder="供应商"
        ></van-field>
        <van-field
          :value="addForm.expect_time"
          name="expect_time"
          data-name="expect_time"
          @input="changeAddFormData"
          required
          clearable
          label="期望送货日期"
          placeholder="期望送货日期"
        ></van-field>
        <van-field
          :value="addForm.remark"
          name="remark"
          data-name="remark"
          @input="changeAddFormData"
          clearable
          label="备注"
          placeholder="请填写备注"
        ></van-field>
      </van-cell-group>
      <van-cell-group v-else-if="order_type == '2'">
        <my-picker
          :form="addForm"
          name="cate_name"
          @click-input="changeName"
          :columns="catarrList"
          value-key="cate_name"
          label="分类"
          placeholder="请选择分类"
        ></my-picker>
        <my-picker
          :form="addForm"
          name="goods_name"
          @click-input="changeGoodsList"
          :columns="goods_list"
          value-key="goods_name"
          label="品名"
          placeholder="请选择品名"
        ></my-picker>
        <my-picker
          :form="addForm"
          name="supplier_name"
          @click-input="changeSupplierType"
          :columns="supplierlist"
          value-key="supplier_name"
          label="供应商名称"
          placeholder="请选择供应商"
        ></my-picker>
        <my-calendar
          :form="addForm"
          name="expect_time"
          @click-input="changeDate"
          label="期望送货日期"
          placeholder="请选择日期"
        >
        </my-calendar>
        <van-field
          :value="addForm.goods_num"
          name="goods_num"
          data-name="goods_num"
          @input="changeAddFormData"
          @blur="changeNumFormat"
          required
          clearable
          label="数量"
          placeholder="请填写数量"
        ></van-field>
        <van-field
          :value="addForm.unit_name"
          name="unit_name"
          data-name="unit_name"
          @input="changeAddFormData"
          required
          clearable
          label="单位"
          placeholder="请输入单位"
          disabled
        ></van-field>
        <van-field
          :value="addForm.goods_price"
          name="goods_price"
          data-name="goods_price"
          @input="changeAddFormData"
          @blur="changeNumFormat"
          required
          clearable
          label="单价"
        ></van-field>
        <my-calendar
          :form="addForm"
          name="productiontime"
          @click-input="changeDate"
          label="生产日期"
          placeholder="请选择生产日期"
        >
        </my-calendar>
        <van-field
          :value="addForm.assurancetime"
          name="assurancetime"
          data-name="assurancetime"
          @input="changeAddFormData"
          required
          clearable
          label="保质期"
          placeholder="请填写保质期"
        ></van-field>
        <van-field
          :value="addForm.address"
          name="address"
          data-name="address"
          @input="changeAddFormData"
          required
          clearable
          label="产地"
          placeholder="请填写产地"
        ></van-field>
        <view class="upload">
          <van-field
            :value="addForm.filesrc"
            name="filesrc"
            data-name="filesrc"
            required
            clearable
            readonly
            label="检测报告"
            placeholder="请上传检测报告"
          >
            <view slot="input">
              <van-uploader
                :deletable="true"
                @delete="deleteImg"
                :fileList="fileList"
                @after-read="afterRead"
                max-count="1"
              />
            </view>
          </van-field>
        </view>
        <van-field
          :disabled="true"
          :value="addForm.nutrition_money | number_format(2)"
          name="nutrition_money"
          data-name="nutrition_money"
          required
          clearable
          label="小计"
        ></van-field>
        <van-field
          :value="addForm.remark"
          name="remark"
          data-name="remark"
          @input="changeAddFormData"
          clearable
          label="备注"
          placeholder="请填写备注"
        ></van-field>
      </van-cell-group>
      <van-cell-group v-else>
        <my-picker
          :form="addForm"
          name="cate_name"
          @click-input="changeName"
          :columns="catarrList"
          value-key="cate_name"
          clearable
          label="分类"
          placeholder="请选择分类"
        ></my-picker>
        <my-picker
          :form="addForm"
          name="goods_name"
          @click-input="changeGoodsList"
          :columns="goods_list"
          value-key="goods_name"
          label="品名"
          placeholder="请选择品名"
        ></my-picker>
        <van-field
          v-if="order_type != '3'"
          :value="addForm.use_type_name"
          name="use_type_name"
          data-name="use_type_name"
          @click-input="pickerShow"
          required
          clearable
          label="使用类型"
          is-link
          placeholder="请选择使用类型"
        ></van-field>
        <van-field
          :value="addForm.goods_num"
          data-name="goods_num"
          :form="addForm"
          name="goods_num"
          @input="changeAddFormData"
          label="数量"
          placeholder="请填写数量"
        ></van-field>
        <van-field
          :form="addForm"
          :value="addForm.unit_name"
          @input="changeFormData"
          data-name="unit_name"
          clearable
          label="单位"
          disabled
        ></van-field>
        <my-picker
          :form="addForm"
          name="supplier_name"
          @click-input="changeSupplierType"
          :columns="supplierlist"
          value-key="supplier_name"
          label="供应商"
          placeholder="请选择供应商"
        ></my-picker>
        <my-calendar
          :form="addForm"
          name="expect_time"
          @click-input="changeDate"
          label="期望送货日期"
          placeholder="请选择日期"
        ></my-calendar>
        <van-field
          :value="addForm.remarks"
          :form="addForm"
          name="remark"
          data-name="remark"
          @input="changeAddFormData"
          clearable
          label="备注"
          placeholder="请填写备注"
        ></van-field>
      </van-cell-group>

      <view class="btn_style">
        <van-button
          color="#999999"
          type="primary"
          class="primary"
          @click="reset"
          >重置</van-button
        >
        <van-button color="#62B158" type="info" @click="okEdit"
          >确认修改</van-button
        >
      </view>
    </view>
    <!-- 使用类型下拉弹框 -->
    <van-popup :show="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="standingList"
        :value-key="value"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      ></van-picker>
    </van-popup>
  </view>
</template>
  
<script>
import myPicker from "../../components/my-picker/my-picker.vue";
export default {
  components: { myPicker },
  data() {
    return {
      fileList: [],
      addForm: {
        unit_name: "", //单位
        filesrc: "", //上传文件
      },
      index: -1,
      catarrList: [], //分类
      cat_id: "", //分类的id
      goods_list: [], //品名
      goods_sn: "", //品名id
      supplierlist: [], //供应商
      showPicker: false,
      standingList: ["学生", "老师"],
      order_type: "",
      setmealList: [], //套餐下拉数据
    };
  },

  // 监听页面加载，该钩子被调用时
  onLoad(options) {
    // this.addForm = wx.getStorageSync("goods_info")[options.index];
    console.log(this.detailData);
    this.addForm = Object.assign({}, this.detailData); // 深拷贝

    this.index = options.index;

    this.getGoods(this.addForm.catarr);
    this.order_type = uni.getStorageSync("order_type"); // 判断
    if (this.order_type == 2) {
      this.fileList.push({
        url: this.detailData.filesrc,
        isImage: true,
        // deletable: true
      });
    }
  },
  watch: {
    addForm: {
      handler(v) {
        if (v.goods_price && v.goods_num) {
          this.$set(
            this.addForm,
            "nutrition_money",
            v.goods_price * v.goods_num
          );
        }
      },
      deep:true
    },
  },
  methods: {
    /*小数位处理*/ 
    numberToFormat(value, max, min) {
      if (!value) return value;
      max = max || 2;
      min = min || 2;
      value = value + "";
      return parseFloat(value).toLocaleString("en", {
        minimumFractionDigits: max,
        maximumFractionDigits: min,
      });
    },
    changeNumFormat(e) {
      this.$set(
        this.addForm,
        e.target.dataset.name,
        this.numberToFormat(e.detail.value, 3, 3)
      );
    },

    /*删除图片（文件）*/ 
    deleteImg(index) {
      this.fileList.splice(index, 1);
      this.$set(this.addForm, "filesrc", "");
    },
    /*文件上传*/ 
    afterRead(event) {
      const { file } = event.detail;
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      wx.uploadFile({
        url: this.API + "/api/purchasemanage/upload", // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: "file",
        formData: { file: "file" },
        header: {
          token: uni.getStorageSync("token"),
        },
        success: (res) => {
          console.log(JSON.parse(res.data).data);

          this.fileList.push({
            ...file,
            url: JSON.parse(res.data).data.fullurl,
            isImage: true,
            // deletable: true
          });
          this.$set(this.addForm, "filesrc", JSON.parse(res.data).data.url); // 上传相对地址或者 绝对地址 ，后期可能需要改
        },
      });
    },
    startUploadFile() {
      wx.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          console.log(res);
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths[0];
          wx.uploadFile({
            url: this.API + "/api/purchasemanage/upload", //仅为示例，非真实的接口地址
            filePath: tempFilePaths,
            name: "file",
            formData: {
              user: "test",
            },
            success: (res) => {
              console.log(res);
              //do something
            },
          });
        },
      });
    },
    /* 获取套餐名下拉数据*/
    async getSetmealList() {
      let res = await this.$ajax.onAddbeforedetail({
        order_type: this.order_type,
      });
      if (res.code == 1) {
        // 套餐类型的套餐名下拉数据
        this.setmealList = res.data.all_menus;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    },

    /*套餐名*/ 
    changeSetmeal(key, value) {
      this.$set(this.addForm, "setmeal_sn", value["setmeal_sn"]); //id
      this.$set(this.addForm, key, value["menu_name"]);

      if (this.addForm.setmeal_sn) {
        this.getCreatemenu();
      }
      this.$set(this.addForm, "goods_num", ""); //老师
      this.$set(this.addForm, "goods_num_stu", ""); //学生
      this.$set(this.addForm, "foods_name", ""); //包含菜名
      this.$set(this.addForm, "supplier_name"); //供应商
      this.$set(this.addForm, "expect_time");
      this.$set(this.addForm, "remarks");
    },
    /*获取相关套餐信息*/ 
    async getCreatemenu() {
      let res = await this.$ajax.onCreatemenu({
        setmeal_sn: this.addForm.setmeal_sn,
      });
      if (res.code == 1) {
        this.addForm.foods_name = res.data.menulistnew.foods_name;
        this.addForm.supplier_name = res.data.menulistnew.supplier_name;
        this.addForm.expect_time = res.data.menulistnew.expect_time;
        this.addForm.supplier = res.data.menulistnew.supplier; //供应商id
        this.addForm.menu_goods_sn = res.data.menulistnew.menu_goods_sn;
        this.addForm.goods_name = res.data.menulistnew.goods_name;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    },
    /*使用身份*/ 
    onConfirm(event) {
      const { picker, value, index } = event.detail;
      this.addForm.use_type_name = value;
      this.addForm.usetype = index;
      this.showPicker = false;
      // 清空对应信息
      this.$set(this.addForm, "goods_num", ""); //数量
      this.$set(this.addForm, "supplier_name");
      this.$set(this.addForm, "expect_time");
      this.$set(this.addForm, "remarks");
    },
    pickerShow() {
      this.showPicker = true;
    },

    changeAddFormData(event) {
      const key = event.target.dataset.name;
      this.addForm[key] = event.detail;
    },

    /*期望送货日期*/ 
    changeDate(key, value) {
      this.$set(this.addForm, [key], value);
      this.dateShow = true;
    },
    /*供应商列表*/ 
    async getSupplierlist() {
      let res = await this.$ajax.getSupplierlist();
      if (res.code == 1) {
        this.supplierlist = res.data;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    },
    changeSupplierType(key, value) {
      this.$set(this.addForm, "supplier", value["supplier"]); // 提交给后台的
      this.$set(this.addForm, [key], value["supplier_name"]);
    },

    /*单位*/ 
    async getUnit() {
      let res = await this.$ajax.getUnit({
        goods_sn: this.goods_sn,
      });
      if (res.code == 1) {
        this.addForm.unit_name = res.data;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    },

    /*品名*/ 
    async getGoods(cat_id) {
      let res = await this.$ajax.getGoods({
        cat_id: cat_id,
      });
      if (res.code == 1) {
        this.goods_list = res.data;
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    },
    /*品名下拉选择数据*/ 
    changeGoodsList(key, value) {
      this.$set(this.addForm, "goods_sn", value["goods_sn"]); // 对应的id 提交给后台的
      this.$set(this.addForm, [key], value["goods_name"]);
      this.goods_sn = this.addForm.goods_sn; //品名（选择的）ID
      this.getUnit(); //单位
      // 每次点击时，清空对应得信息
      this.$set(this.addForm, "unit_name", "");
      this.$set(this.addForm, "use_type_name", ""); //使用类型
      this.$set(this.addForm, "goods_num", ""); //数量
      this.$set(this.addForm, "supplier_name");
      this.$set(this.addForm, "expect_time");
      this.$set(this.addForm, "remarks");
    },

    /*分类*/ 
    async getBeforeDetail() {
      let res = await this.$ajax.getBeforeDetail({
        cat_id: this.cat_id,
      });
      if (res.code == 1) {
        this.catarrList = res.data.catarr; //分类
      }
    },

    /*分类下拉选择数据显示（封装）*/ 
    changeName(key, value) {
      this.$set(this.addForm, "catarr", value["catarr"]); // // 对应的id 提交给后台的
      this.$set(this.addForm, [key], value["cate_name"]);
      this.cat_id = this.addForm.catarr; //id
      // 调品名数据
      this.getGoods(this.cat_id); //品名
      // 每次修改分类 腰清空产品
      this.$set(this.addForm, "goods_name", "");
      this.$set(this.addForm, "goods_sn", "");
      this.$set(this.addForm, "unit_name", "");
      this.$set(this.addForm, "use_type_name", ""); //使用类型
      this.$set(this.addForm, "goods_num", ""); //数量
      this.$set(this.addForm, "supplier_name");
      this.$set(this.addForm, "expect_time");
      this.$set(this.addForm, "remarks");
    },

    changeFormData(event) {
      const key = event.target.dataset.name;
      this.addForm[key] = event.detail;
    },
    /*确认修改*/ 
    okEdit() {
      // var goods_info = wx.getStorageSync("goods_info"); // 取值
      // goods_info.splice(this.index, 1, { ...this.addForm }); // 修改
      // wx.setStorageSync("goods_info", Object.assign([], goods_info)); // 存储 拱提交页面使用  将productList 数据存储在本地 浅拷贝 将productList 拷贝在一个空数组里面 然后将新的数组里面的数据赋值给productList里面
      uni.setStorageSync("saveDetail", true);
      wx.navigateBack();
    },

    /*重置*/ 
    reset() {
      this.addForm = {};
    },
  },

  mounted() {
    this.getBeforeDetail(); //分类
    this.getSupplierlist(); //供应商
    this.getSetmealList(); //套餐下拉数据
  },

  // 监听页面显示，页面每次出现在屏幕上都触发
  onShow() {
    uni.setNavigationBarTitle({
      title: " 采购商品 - 编辑",
    });
  },

  // 监听用户下拉动作，一般用于下拉刷新
  onPullDownRefresh() {},

  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
};
</script>
  
<style lang="scss">
.upload {
  height: 160rpx;

  .van-field__body {
    height: 180rpx;
  }
}

.purchaseDetails {
  width: 100%;
  height: 100vh;
  background: rgba(255, 255, 255, 1);
  padding: 20rpx 0;

  .details_box {
    width: 100%;

    .title {
      padding: 10rpx 20rpx;
      color: rgba(16, 16, 16, 1);
      font-size: 28rpx;
      font-family: SourceHanSansSC-medium;
    }

    .btn_style {
      margin-top: 50rpx;
      display: flex;
      justify-content: space-evenly;

      .van-button {
        width: 180rpx;
        height: 72rpx;
        border-radius: 10rpx;
      }
    }
  }
}
</style>